package com.example.gitpart03;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.gitpart03.R;
import com.example.gitpart03.Book;

import java.util.List;

public class BookListAdapter extends RecyclerView.Adapter<BookListAdapter.BookViewHolder> {

    private Context context;
    private List<Book> bookList;
    private OnItemClickListener listener;

    public BookListAdapter(Context context, List<Book> bookList) {
        this.context = context;
        this.bookList = bookList;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    @NonNull
    @Override
    public BookViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_book, parent, false);
        return new BookViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull BookViewHolder holder, int position) {
        Book book = bookList.get(position);

        holder.textViewTitle.setText(book.getTitle());
        holder.textViewAuthor.setText("作者: " + book.getAuthor());
        holder.textViewChapters.setText("章节数: " + book.getChapters());
        holder.textViewDescription.setText(book.getDescription());

        // 使用Glide加载封面图
        Glide.with(context)
                .load(book.getCoverUrl())
                .placeholder(R.drawable.ic_book_placeholder)
                .error(R.drawable.ic_book_error)
                .into(holder.imageViewCover);

        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(book);
            }
        });
    }

    @Override
    public int getItemCount() {
        return bookList.size();
    }

    public class BookViewHolder extends RecyclerView.ViewHolder {
        ImageView imageViewCover;
        TextView textViewTitle;
        TextView textViewAuthor;
        TextView textViewChapters;
        TextView textViewDescription;

        public BookViewHolder(@NonNull View itemView) {
            super(itemView);
            imageViewCover = itemView.findViewById(R.id.imageViewCover);
            textViewTitle = itemView.findViewById(R.id.textViewTitle);
            textViewAuthor = itemView.findViewById(R.id.textViewAuthor);
            textViewChapters = itemView.findViewById(R.id.textViewChapters);
            textViewDescription = itemView.findViewById(R.id.textViewDescription);
        }
    }

    public interface OnItemClickListener {
        void onItemClick(Book book);
    }
}